<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="6"
              ><span class="el-custom-title"
                >工艺类型</span
              ></el-col
            >
            <el-col :span="18">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >添加</el-button
                >
                <el-button type="primary"
                 icon="el-icon-edit"
                 size="mini" @click="handleUpdate()">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-tree
              ref="tree2"
              :data="data2"
              :props="defaultProps"
              class="filter-tree"
              default-expand-all
              @node-click="clickNode"
            />
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="4"
              ><span class="el-custom-title"
                >工艺流程</span
              ></el-col
            >
            <el-col :span="20" style="float: right">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreateSon"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleUpdateSon()"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="ui_deleteSon(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @selection-change="handleSelectionChangeSon"
              @row-click="rowClick"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="编号"
                width="95"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyFlowNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="名称"
                width="120"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyFlowName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="类型名称"
                width="120"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.technologyFlowTypeName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="顺序"
                width="60"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.ordered }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="描述"
                width="95"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.description }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="父流程id"
                width="95"
                style="display: none"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.parentid }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="父流程编号"
                width="95"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.parentNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="父流程名称"
                width="120"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.parentName }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total2 > 0"
              :total="total2"
              :page.sync="listQuery2.page"
              :limit.sync="listQuery2.limit"
              :page-sizes="listQuery2.pageSizes"
              @pagination="fetchDataSon"
            />
          </el-row>
        </div>
        <div style="padding: 10px">
          <mestechnologysetchild
            :mestechnologyflowid="this.currentMESTechnologyFlowTypeId"
            @refreshSteps="refreshSteps"
            style="width: 100%"
          ></mestechnologysetchild>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <div class="app-container">
        <el-row>工艺流程顺序</el-row>
        <el-row>
        <el-steps :active="2" align-center>
          <el-step
            :title=itm.technologySetName
            :description=itm.comment
            v-for="itm in lstSetFlows"
            :key=itm.ordered
          ></el-step>
        </el-steps>
        </el-row>
  
      </div>
    </el-row>
    <el-dialog
      :title="textMap[dialogStatusSon]"
      :visible.sync="dialogFormVisibleSon"
    >
      <el-form
        ref="dataFormson"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工艺流程编号" prop="technologyFlowNo">
          <el-input v-model="tempson.technologyFlowNo" />
        </el-form-item>
        <el-form-item label="工艺流程名称" prop="technologyFlowName">
          <el-input v-model="tempson.technologyFlowName" />
        </el-form-item>
        <el-form-item label="工艺类型" prop="technologyFlowTypeId">
          <el-select
            v-model="tempson.technologyFlowTypeId"
            class="filter-item"
            placeholder="请选择工艺流程类型"
            @change="handleTechnologyFlowTypeChange"
          >
            <el-option
              v-for="item in this.ddTechnologyFlowTypes"
              :key="item.id"
              :label="item.technologyFlowTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="顺序号" prop="ordered">
          <el-input v-model="tempson.ordered" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="tempson.description" />
        </el-form-item>
        <el-form-item label="父流程id" prop="parentid">
          <el-select-tree
            :default-expand-all="defaultExpandAll"
            :multiple="multiple"
            :placeholder="placeholder"
            :disabled="disabled"
            :data="data"
            :props="defaultProps"
            :check-strictly="checkStrictly"
            :clearable="clearable"
            v-model="tempson.parentId"
            @change="selectChange"
            show-checks
          ></el-select-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSon = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatusSon === 'create' ? ui_createSon() : ui_updateSon()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="工艺流程类型编号" prop="technologyFlowTypeNo">
          <el-input v-model="temp.technologyFlowTypeNo" />
        </el-form-item>
        <el-form-item label="工艺流程类型名称" prop="technologyFlowTypeName">
          <el-input v-model="temp.technologyFlowTypeName" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon,
} from "@/api/mesTechnologyFlow";

import {
  getAll,
  getList,
  create,
  update,
  deleteBatch,
} from "@/api/mesTechnologyFlowType";

import { getAll as getAllTechnologyFlowTypes } from "@/api/mesTechnologyFlowType";

import ElSelectTree from "el-select-tree";

import mestechnologysetchild from "@/views/technology/mestechnologysetchild";

export default {
  components: { Pagination, ElSelectTree, mestechnologysetchild },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      data: [],
      data2: [],
      defaultProps: {
        value: "id",
        children: "children",
        label: "technologyFlowName",
      },
      list2: null,
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14],
      },
      currentMESTechnologyFlowTypeId: 0,
      dialogFormVisibleSon: false,
      dialogStatusSon: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      rulesson: {
        technologyFlowNo: [
          {
            required: true,
            message: "工艺流程编号不能为空！",
            trigger: "change",
          },
        ],
        technologyFlowName: [
          {
            required: true,
            message: "工艺流程名称不能为空！",
            trigger: "change",
          },
        ],
        technologyFlowTypeId: [
          {
            required: true,
            message: "工艺类型ID不能为空！",
            trigger: "change",
          },
        ],
        ordered: [
          {
            required: true,
            message: "顺序号不能为空！",
            trigger: "change",
          },
        ],
        description: [
          {
            required: true,
            message: "描述不能为空！",
            trigger: "change",
          },
        ],
      },
      tempson: {
        id: 0,
        technologyFlowNo: "",
        technologyFlowName: "",
        technologyFlowTypeId: 0,
        ordered: "",
        description: "",
        parentid: 0,
      },
      //表格變量
      lstSelectedSon: [],
      ddTechnologyFlowTypes: [],
      currentTypeId: 0,
      currentParentId: 0,
      rules: {
        technologyFlowTypeNo: [
          {
            required: true,
            message: "工艺流程类型编号不能为空！",
            trigger: "change",
          },
        ],
        technologyFlowTypeName: [
          {
            required: true,
            message: "工艺流程类型名称不能为空！",
            trigger: "change",
          },
        ],
      },
      temp: {
        id: 0,
        technologyFlowTypeNo: "",
        technologyFlowTypeName: "",
        comment: "",
      },
      dialogStatus: "",
      dialogFormVisible: false,
      displayTree: false,
      clearable: true,
      defaultExpandAll: true,
      multiple: false,
      placeholder: "请选择",
      disabled: false,
      checkStrictly: true,
      lstSetFlows:[],
    };
  },
  watch: {},
  computed: {},
  created() {
    this.fetchData();
    this.fetchDataSon();
    this.getAllTechnologyFlowTypes();
  },
  methods: {
    fetchData() {
      this.data2 = [];
      this.listLoading = true;
      let params = {
        name: "",
      };
      getAllSon(params).then((response) => {
        this.data2.length = 0;
        this.data2.push(response.data);
        this.data.length = 0;
        this.data.push(response.data);
        this.listLoading = false;
      });
    },
    handleSelectionChangeSon(val) {
      if (val == null || val.length == 0) return;
      this.lstSelectedSon = val;
    },
    fetchDataSon() {
      let params = {
        MESTechnologyFlowTypeId: this.currentTypeId,
        page: this.listQuery2.page,
        size: this.listQuery2.limit,
      };
      return listSon(params).then((response) => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    rowClick(row, column, event) {
      this.currentMESTechnologyFlowTypeId = row.id;
      let index = this.ddTechnologyFlowTypes.find(
        (v) => v.technologyFlowTypeName == row.technologyFlowTypeName
      );
      if (index != null) {
        this.tempson.technologyFlowTypeId = index.id;
      }
    },
    resetTempSon() {
      this.temp = {
        id: 0,
        technologyFlowNo: "",
        technologyFlowName: "",
        technologyFlowTypeId: 0,
        ordered: "",
        description: "",
        parentid: 0,
      };
    },
    handleCreateSon() {
      this.resetTempSon();
      this.dialogStatusSon = "create";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    handleUpdateSon() {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length !== 1) {
        this.$message.error("请先选择一条工艺流程");
        return;
      }
      this.tempson = Object.assign({}, this.lstSelectedSon[0]); // copy obj
      let index = this.ddTechnologyFlowTypes.find(
        (v) =>
          v.technologyFlowTypeName ==
          this.lstSelectedSon[0].technologyFlowTypeName
      );
      if (index != null) {
        this.tempson.technologyFlowTypeId = index.id;
      }
      this.tempson = { ...this.tempson };
      this.dialogStatusSon = "update";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    ui_createSon() {
      this.$refs["dataFormson"].validate((valid) => {
        if (valid) {
          this.tempson.id = 0; //自增
          createSon(this.tempson).then((response) => {
            this.list2.unshift(this.tempson);
            //主要是新增后id不为0 ！！！
            this.tempson.id = response.data.id;
            this.updateTree(false);
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    ui_updateSon() {
      this.$refs["dataFormson"].validate((valid) => {
        if (valid) {
          updateSon(this.tempson).then((response) => {
            const index = this.list2.findIndex((v) => v.id === this.tempson.id);
            this.list2.splice(index, 1, this.tempson);
            //更新树
            this.tempson.id = response.data.id;
            this.updateTree(false);
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    ui_deleteSon(row, index) {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length === 0) {
        this.$message.error("请先选择要删除的ActionTherbligs");
        return;
      }
      let ids = [];
      this.lstSelectedSon.map(function (elm) {
        ids.push(elm.id);
      });
      deleteBatchSon(ids).then(() => {
        ids.forEach((elm) => {
          const index = this.list2.findIndex((v) => v.id === elm);
          this.list2.splice(index, 1);
        });
        this.updateTree(true);
        this.dialogFormVisibleSon = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000,
        });
      });
    },
    handleMainTypeChange(val) {
      this.tempson.mESTechnologyFlowTypeId = val;
      this.tempson = { ...this.tempson };
    },
    clickNode(data, node, obj) {
      this.lstSelected = [];
      if (data.parentId == -1) return;
      this.lstSelected.push(data);
      this.temp = Object.assign({}, data);
      let params = {
        technologyFlowTypeId: data.id,
        page: this.listQuery2.page,
        size: this.listQuery2.limit,
      };
      listSon(params).then((response) => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    getAllTechnologyFlowTypes() {
      getAllTechnologyFlowTypes().then((response) => {
        this.ddTechnologyFlowTypes.push({
          id: 0,
          technologyFlowTypeName: "请选择",
        });
        this.ddTechnologyFlowTypes.push(...response.data);
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length !== 1) {
        this.$message.error("请先选择一条工艺流程");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.temp.therbligsTypeId = this.currentTherbligsTypeId;
      this.temp = { ...this.temp };
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    ui_create() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.temp.id = 0; //自增
          create(this.temp).then(() => {
            this.updateTree(false);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          update(this.temp).then(() => {
            this.updateTree(false);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000,
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的ActionTherbligs");
        return;
      }
      let ids = [];
      this.lstSelected.map(function (elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        this.updateTree(true);
        this.dialogFormVisibleSon = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000,
        });
      });
    },
    updateTree(isDel) {
      //先找到工段(更新)
      if (
        this.data2 != null &&
        this.data2[0].children != null &&
        this.data2[0].children.length > 0
      ) {
        let technologyFlowType = this.data2[0].children.find(
          (v) => v.id == this.tempson.technologyFlowTypeId
        );
        if (technologyFlowType != null) {
          if (this.tempson.parentId == 0) {
            //从第三级找
            if (this.tempson.id > 0) {
              //更新
              let idx = technologyFlowType.children.findIndex(
                (v) => v.id == this.tempson.id
              );
              if (idx >= 0) {
                if (!isDel) {
                  technologyFlowType.children.splice(idx, 1, this.tempson);
                } //删除
                else if (isDel) {
                  technologyFlowType.children.splice(idx, 1);
                } //增加
                else {
                  technologyFlowType.children.push(this.tempson);
                }
              }
            }
          } //从第四级找
          else {
            let parentIdx = technologyFlowType.children.findIndex(
              (v) => v.id == this.tempson.parentId
            );
            if (parentIdx >= 0) {
              let parent = technologyFlowType.children[parentIdx];
              if (this.tempson.id > 0) {
                //更新
                let idx = parent.children.findIndex(
                  (v) => v.id == this.tempson.id
                );
                if (!isDel && idx >= 0) {
                  parent.children.splice(idx, 1, this.tempson);
                } //删除
                else if (isDel) {
                  parent.children.splice(idx, 1);
                } else {
                  //增加
                  parent.children.push(this.tempson);
                }
              }
            }
          }
        }
      }
    },
    resetTemp() {
      this.temp = {
        id: 0,
        technologyFlowTypeNo: "",
        technologyFlowTypeName: "",
        comment: "",
      };
    },
    handleTechnologyFlowTypeChange(val) {
      let param = {
        technologyFlowTypeId: val == null ? 0 : val,
      };
      getAllSon(param).then((response) => {
        this.data.length = 0;
        this.data = response.data.children;
      });
    },
    selectChange(e) {
      console.log(e);
    },
    refreshSteps(val) {

       this.lstSetFlows = val;
    },
  },
};
</script>
